import React, { useEffect, useState } from 'react';
import GopherProps from '../objects/internal/GopherProps';
import { Select } from 'antd';

const {Option} = Select;

export interface AsyncCitySelectorProps extends GopherProps {
	onChange: (x: string) => void;

	disabled?: boolean;
	promptReload?: number;
	keepAllOption?: boolean;
}

export default function AsyncCitySelector(props: AsyncCitySelectorProps) {
	const [loading, setLoading] = useState(true);
	const [cities, setCities] = useState<string[]>([]);

	useEffect(() => {
		console.log('city selector update');
		props.gopher.getKnownCities().then(cities => {
			setLoading(false);
			setCities(props.keepAllOption ? (['全部']).concat(cities) : cities);
		});
	}, [props.gopher, props.keepAllOption, props.promptReload]);

	return (
		<Select defaultValue={props.keepAllOption ? '全部' : ''} loading={loading} disabled={props.disabled}
				onChange={(x) => props.onChange(x)}>{cities.map((it, index) => <Option value={it}
																							 key={index}>{it}</Option>)}</Select>
	);
}
